<?php
namespace control;
/*
*工序巡检类
*/

class processSpotCheckClass extends adIndexClass
{
    private const page = 'processSpotCheck';
    private const table = 'quality_order';
    private const title = '工序巡检';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'startDate'          => [
                        'name'  => "计划开工日期",
                        'width' => 100,
                    ],
                    'sourceNo'  => [
                        'name'  => '关联单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 150,
                    ],
                    'process'         => [
                        'name'  => '工序',
                        'width' => 150,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 100,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'batch'          => [
                        'name'  => '批次',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '检验数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'passNum'          => [
                        'name'  => '合格数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'badNum'          => [
                        'name'  => '不良数量',
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ],
                    'checkTime'          => [
                        'name'  => '质检日期',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name' => 'state', 'value' => ['待质检', '已质检'], 'checked' => ['待质检'])),
                ],
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    '生产线' => selectMultiple(array("name" => "lineId", "table" => "product_line",'where'=>"coid = '".self::$coid."'", 'field' => "concat(workshop,'-',name) as name,id", 'sqlField' => 'name', 'sqlId' => 'id')),
                    '工序' => selectMultiple(["name" => "processId", 'table' => "process", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                ],
                [
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称" => text(array("name" => "materialName")),
                    "不良原因" => text(array("name" => "reason")),
                ],
                [
                    '处置方式' => repeatSelect(array('name' => 'method', 'sqlForm' => " quarantine_reason where coid = '" . self::$coid . "'", 'sqlField' => 'method')),
                    "质检日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . $this->get('cla') . "','operate',{act:'batch'})\" class='spanButton'>批量质检</span>\n
                <span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.sourceNo" => $this->post('orderNo'),
            "b.code" => $this->post('code'),
            "b.materialName" => $this->post('materialName'),
        );
        //全等查询数组
        $equal = array(
            'a.coid' => self::$coid,
            'a.processId'=>$this->post('processId'),
            'a.targetId'=>$this->post('lineId')
        );
        $and = " and a.type = 6";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'checkTime');
        }
        if ($this->post('reason')) {
            $and .= " and a.id in (select distinct orderId from quality_order_reason where coid = '" . self::$coid . "' and reasonId in (select id from quarantine_reason where coid = '" . self::$coid . "' and reason like '%" . $this->post('reason') . "%')) ";
        }
        if ($this->post('method')) {
            $and .= " and a.id in (select distinct orderId from quality_order_reason where coid = '" . self::$coid . "' and reasonId in (select id from quarantine_reason where coid = '" . self::$coid . "' and dealMethod = '" . $this->post('method') . "')) ";
        }
        if ($this->post('state')) {
            $and .= " and a.state in ('".implode("','",$this->post('state'))."')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.time desc,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join material as b on a.materialId = b.id",
            'field' => "a.*,b.name,b.code,b.model",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $machining_send_order = query('machining_send_order',"id = '$array[sourceId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'startDate':
                        $row[] = $machining_send_order['startDate'];
                        break;
                    case 'line':
                        $line= query('product_line', "id = '$array[targetId]'");
                        $row[] = $line['workshop'].'-'.$line['name'];
                        break;
                    case 'process':
                        $process= query('process', "id = '$machining_send_order[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'num':
                    case 'passNum':
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case 'badNum':
                        $row[] = $array['state'] == '待质检' ? 0 : self::lostZero($array['num'] - $array['passNum'],'numPrecision');
                        break;
                    case 'checkTime':
                        $row[] = self::null($array['checkTime']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function getSendOrder(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $json['data'] = [];
        $where = " and coid='".self::$coid."' and classify = '生产派工' and state = '已确认' and routingMxId in (select id from routing_detail where coid = '".self::$coid."' and orderId = machining_send_order.routingId and method = '巡检')";
        if ($val){
            $where.=" and orderNo like '%$val%'";
        }
        $page = $this->page(array(
            'field' => " orderNo as title,id ",
            "table" => 'machining_send_order',
            "where" => $where,
            "order" => ' startDate asc ',
        ));
        $json['pageAll'] = $page['para']['pageAll'];
        $json['data'] = $page['array'];
        $json['warn'] = 2;
        return json_encode($json, 320);
    }
    public function getOrderInfo(){
        $machining_send_order = query('machining_send_order',"id = '".$this->post('id')."'");
        $line = query('product_line',"id = '$machining_send_order[lineId]'");
        $process = query('process',"id = '$machining_send_order[processId]'");
        if (empty($process['qualityItem'])) {
            $json['warn'] = "未找到工序【{$process['name']}】的质检项";
        }else{
            $qItem[] = ['', '质检项','结果选项','备注'];
            $all = explode('，', $process['qualityItem']);
            foreach ($all as $k=>$val) {
                $itemId = suiji();
                $qItem[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this)").
                    hidden(array('name'=>'itemId[]','value'=>$itemId)).
                    hidden(array('name'=>'itemName[]','value'=>$val)),
                    $val,
                    radio(array('name' => "resultOption[$itemId]", 'checked' => '合格', 'value' => ['合格', '不合格'])),
                    text(array('name' => 'itemText[]', 'class' => 'text')),
                ];
            }
            $reason[]= ['', '不良原因','不良数量','处置方式','备注'];
            $reason[] = $this->listRow(['reasonId' => self::getId(), 'list' => 1], $process['id']);
            $total      = [
                2  => "<span id='total_num'>0</span>",
            ];

            $json['warn'] = 2;
            $setting = optionSettingClass::getSetting('质量');
            if (!isset($setting['checkOrderDefault']['val']) && $setting['checkOrderDefault']['val'] !='单据数量'){
                $machining_send_order['num']=0;
            }
            $json['data'] = [
                'line'=>$line['workshop'].'-'.$line['name'],
                'process'=>$process['name'],
                'recordDate'=>$machining_send_order['startDate'],
                'material'=>materialClass::getName($machining_send_order['materialId']),
                'planNum'=>self::lostZero($machining_send_order['num'],'numPrecision'),
                'unit'=>$machining_send_order['unit'],
                'processId'=>$process['id'],
                'item'=>"<p>质检项目</p>".$this->listTable(array('tr'=>$qItem, 'end' => true)),
                'reason'=>"<p>不良明细</p>".$this->listTable(array('tr' => $reason, 'end' => true, 'total' => $total)),
            ];
        }
        return json_encode($json,320);

    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $cla = self::page;
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        $machining_send_order = query('machining_send_order',"id = '".$info['sourceId']."'");
        $process = query('process',"id = '$machining_send_order[processId]'");
        $qItem[]= ['', '质检项','结果选项','备注', '操作'];
        $reason[]= ['', '不良原因','不良数量','处置方式','备注'];
        $result = find(array(
            'field' => "id as reasonId,reasonId as reasonOption,num as reasonNum,dealMethod,text as mxText",
            'table' => self::table . "_reason where orderId = '$info[id]' order by list"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $reason[] = $this->listRow($array, $process['id']);
            }
        }else{
            if($process['id']) {
                $reason[] = $this->listRow(['reasonId' => self::getId(), 'list' => 1], $process['id']);
            }
        }
        $total      = [
            2  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'reasonNum')),'num') . "</span>",
        ];

        $result = find(array('table' => self::table . "_item", 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $qItem[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name'=>'itemId[]','value'=>$array['id'])).
                hidden(array('name'=>'itemName[]','value'=>$array['itemId'])),
                $array['itemId'],
                radio(array('name' => "resultOption[$array[id]]", 'checked' => '合格', 'value' => ['合格', '不合格'])),
                text(array('name' => 'itemText[]', 'class' => 'text')),
            ];
        }
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $line = query('product_line',"id = '$info[targetId]'");
        $process = query('process',"id = '$info[processId]'");
        $materialName = materialClass::getName($info['materialId']);
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must."关联派工单号：" => componentClass::selectText([
                        'name'      => 'sourceId',
                        'value'     => $info['sourceId'],
                        'title' => $machining_send_order['orderNo'],
                        'cla'       => $cla,
                        'fun'       => 'getSendOrder',
                        'change'    => 'dataAssign',
                    ]).
                        <<<eof
<script>
function dataAssign(data){
    $.post(root+'control/adIndex.html?cla=$cla&fun=getOrderInfo',{id:data.id},function(res) {
       if (res.warn ==2){
          $("#product_line").html(res.data.line);
          $("#process").html(res.data.process);
          $("[name='processId']").val(res.data.processId);
          $("#recordDate").html(res.data.recordDate);
          $("#material").html(res.data.material);
          $("#planNum").html(res.data.planNum);
          $("[name='num']").val(res.data.planNum);
          $("[name='passNum']").val(res.data.planNum);
          $("#quality_order_item").empty().append(res.data.item);
          $("#quality_reason").empty().append(res.data.reason);
          $(".num-unit").html(res.data.unit)
       }else{
           msg(res.warn,'error')
       }
      
   },'json')
}
function calculateNum(e){
    let badNum = 0;
    $("[name='reasonNum[]']").each(function(res) {
       badNum+=Number($(this).val());
    })
    let sendId = $("[name='sourceId']").val();
    let num = $("[name='num']").val();
    let passNum = $("[name='passNum']").val();
    $.post(root+'control/adIndex.html?cla=$cla&fun=calculateNum',{sendId:sendId,num:num,badNum:badNum,passNum:passNum},function(res) {
        $("[name='num']").val(res.data.num);
        $("[name='passNum']").val(res.data.passNum);
    },'json')
}
</script>
eof,
                    "生产线：" =>"<span id='product_line'>{$line['workshop']}-{$line['name']}</span>",
                    "工序：" => "<span id='process'>{$process['name']}</span>".hidden(array('name'=>'processId','value'=>$machining_send_order['processId'])),
                    "计划开工日期：" => "<span id='recordDate'>{$machining_send_order['startDate']}</span>",
                ],
                [
                    "物料：" => "<span id='material'>$materialName</span>",
                    "计划数量(<span class='num-unit'>{$machining_send_order['unit']}</span>)：" => "<span id='planNum'>".self::lostZero($machining_send_order['num'],'numPrecision')."</span>",
                    "检验数量(<span class='num-unit'>{$machining_send_order['unit']}</span>)：" => text(array('name'=>'num', 'other' => self::digitalFiltering('numPrecision'),'value'=>self::lostZero($info['num'],'numPrecision'))),
                    "合格数量(<span class='num-unit'>{$machining_send_order['unit']}</span>)：" => text(array('name'=>'passNum', 'other' => self::digitalFiltering('numPrecision'),'value'=>self::lostZero($info['passNum'],'numPrecision'))),
                ],
            ],
            '检验方案' => [
                [
                    "质检方式:"=>'巡检',
                ],
                [
                    "备注：" => textarea(array('name'=>'text','value'=>$info['text'],'class'=>'textarea')),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => '质检项目',
            'id' => 'quality_order_item',
            'html' => $this->listTable(array('tr'=>$qItem, 'end' => true)),
        ]);
        $body .= $this->editList([
            'title' => '不良明细',
            'id' => 'quality_reason',
            'html' => $this->listTable(array('tr' => $reason, 'end' => true, 'total' => $total)),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $this->get('id')]),
            'button'=> ' '
        ]);
        $data['html'].=<<<eof
<script>
function addRow(e){
        let qid = $("[name='processId']").val();
        if (!qid){
            msg('请先选择派工单','error')
            return false;
        }
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{qid:qid},function (res){
                $(e).closest('tr').after(res.data);
                resetNumber($(e).closest('tbody'))
                calculateTotal()
             },'json');
}
//计算计划数量
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0
    table.find("[name='reasonNum[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>
eof;

        //返回
        return $this->tab($data);
    }

    /**
     * 检验单修改不合格数量时控制
     * @return false|string
     */
    public function calculateNum(){
        $passNum = $this->post('passNum')?:0;
        $num = $this->post('num')?:0;
        $badNum = $this->post('badNum')?:0;
        $setting = optionSettingClass::getSetting('质量');
        if($passNum ==0 && $num ==0){
            $json['data']['num'] = 0;
            $json['data']['passNum'] = 0;
        }elseif(isset($setting['checkOrderBad']['option']) && $setting['checkOrderBad']['option'] &&$setting['checkOrderBad']['val'] =='checkNum'){
            //合格数量不变，计算检验数量
            $json['data']['num'] = self::formattingFigure($badNum+$passNum,'numPrecision');
            $json['data']['passNum'] = $passNum;
        }else{
            //检验数量不变，计算合格数量
            $json['data']['num'] =$num;
            $json['data']['passNum'] =  self::formattingFigure($num-$badNum,'numPrecision');
        }
        return json_encode($json,320);
    }

    /**
     * Desc : 不良原因
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @param string $processId
     * @return array|false|string
     */
    public function listRow($data=[], $processId = '')
    {
        $processId = $processId?:$this->post('processId');
        $process = query('process',"id = '$processId'");
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['reasonId'])&&$data['reasonId']?$data['reasonId']:self::getId();
        $field = ['reasonOption', 'reasonNum', 'dealMethod', 'mxText'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
            'para' => ['processId'=>$processId],
            'callback' => "calculateTotal()",
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg);calculateTotal()","cloneRows(this,$cloneArg)", "addRow(this,'$processId')"),
            hidden(array('name' => 'reasonId[]', 'value' => $mxId)) .
            select(array('name' => 'reasonOption[]', 'class' => 'select', 'value' => $array['reasonOption'], 'option' => explode('，', $process['defectType']), 'title' => '请选择')),
            text(array('name' => 'reasonNum[]', 'other' => self::digitalFiltering('numPrecision'), 'blur'=>"calculateTotal();calculateNum", 'value' => self::lostZero($array['reasonNum'],'numPrecision'))),
            select(array('name' => 'dealMethod[]', 'class' => 'select', 'value' => $array['dealMethod'], 'option' => explode('，', para('dealMethod')), 'title' => '请选择')),
            text(array('name' => 'mxText[]', 'class' => 'text', 'value' => $array['mxText'])),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $processId = $this->post('qid');//工序ID
        $res = json_decode($this->listRow(processId: $processId),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }

    /**
     * 提交
     * @return bool|string
     */
    public function editEdit()
    {
        $id = $this->post('id')?:suiji();
        $itemIdArr = $this->post('itemId') ?: [];
        $resultOptionArr = $this->post('resultOption');
        $itemTextArr = $this->post('itemText');
        $reasonIdArr = $this->post('reasonId')?:[];
        $reasonOptionArr = $this->post('reasonOption');
        $reasonNumArr = $this->post('reasonNum')?:[];
        $mxTextArr = $this->post('mxText');
        $dealMethodArr = $this->post('dealMethod') ?: [];
        $itemNameArr = $this->post('itemName');

        $field = [
            'num'=>$this->post('num')?self::formattingFigure($this->post('num'),'numPrecision'):'',
            'passNum' => $this->post('passNum')?self::formattingFigure($this->post('passNum'),'numPrecision'):'',
            'sourceId'=>$this->post('sourceId'),
            'text'=>$this->post('text')
        ];
        $annotation = [
            'num' => '检验数量',
            'passNum' => '合格数量',
        ];
        $rules = [
            'num' => 'required|numeric',
            'passNum' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        $machining_send_order = query('machining_send_order', "id = '$field[sourceId]'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($itemIdArr)) {
            $json['warn'] = '未找到质检项目';
        } elseif (static::is_null_array($resultOptionArr)) {
            $json['warn'] = '请选择结果选项';
        } elseif (!empty($reasonIdArr) && static::is_null_array($reasonNumArr)) {
            $json['warn'] = '请填写不良数量';
        }elseif($field['num']<$field['passNum']){
            $json['warn'] = '合格数量超出了检验数量';
        } elseif (round(array_sum($reasonNumArr),2) != round($field['num'] - $field['passNum'],2)) {
            $json['warn'] = '不良明细中数量之和不等于总的不良数量';
        } elseif($field['num'] > $machining_send_order['num']){
            $json['warn'] = '检验数量已超出了计划数量';
        }else {
            $json['warn'] = '';
            //判断属于生产计划单的数量是否超过总数量
            foreach ($reasonNumArr as $k => $val) {
                if ($val  > round($field['num']-$field['passNum'],2)) {
                    $json['warn'] = "不良明细中不良数量和超过了总的不良数量";
                    break;
                }
            }

            if (empty($json['warn'])) {
                $this->startTrans();
                $userNo = codeTemplateClass::generateCode('processSpotCheck',[
                    'prefix' => 'IN' . date('Ymd'),
                    'table' => 'quality_order',
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $batch = static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and sourceId = '$field[sourceId]'"));
                if(empty($info['id'])){
                    $field = array_merge($field,[
                        'id'=>$id,
                        'coid'=>self::$coid,
                        'state'=>'待质检',
                        'type' => 6,
                        'sourceTable' => 'machining_send_order',
                        'targetId' => $machining_send_order['lineId'],
                        'inventoryId' => '',
                        'warehouseId' => '',
                        'processId' => $machining_send_order['processId'],
                        'materialId' => $machining_send_order['materialId'],
                        'unit' => $machining_send_order['unit'],
                        'orderNo' => $userNo,
                        'batch' => $userNo . '-' . ($batch+1),
                        'qid' => '',
                        'sourceNo' => $machining_send_order['orderNo'],
                    ]);
                    $json['warn'] = static::insert(array(
                       'table'=>self::table,

                       'field'=>$field
                    ));
                }else{
                    $field = array_merge($field,[
                        'targetId' => $machining_send_order['lineId'],
                        'inventoryId' => '',
                        'warehouseId' => '',
                        'processId' => $machining_send_order['processId'],
                        'materialId' => $machining_send_order['materialId'],
                        'unit' => $machining_send_order['unit'],
                        'orderNo' => $userNo,
                        'batch' => $userNo . '-' . ($batch+1),
                        'qid' => '',
                        'sourceNo' => $machining_send_order['orderNo'],
                    ]);
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where
                    ]);
                }
                foreach ($itemIdArr as $k => $nid) {
                    $mx = query(self::table."_item", "id = '$nid'");
                    if ($mx['id']){
                        $warn = static::update([
                            "table" => self::table."_item",
                            "field" => [
                                'itemId'=>$itemNameArr[$k],
                                'options' => $resultOptionArr[$nid],
                                'text' => $itemTextArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);

                    }else{
                        $warn = static::insert([
                            "table" => self::table."_item",
                            "field" => [
                                'orderId' => $id,
                                'id'=>$nid,
                                'coid'=>self::$coid,
                                'itemId'=>$itemNameArr[$k],
                                'options' => $resultOptionArr[$nid],
                                'text' => $itemTextArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
                //添加或更新质检不良原因
                if (is_array($reasonIdArr)) {
                    foreach ($reasonIdArr as $k => $nid) {
                        $mx = query(self::table."_reason", "id = '$nid'");
                        $reasonNumArr[$k] = self::formattingFigure($reasonNumArr[$k],'numPrecision');
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table."_reason",
                                "field" => [
                                    'reasonId' => $reasonOptionArr[$k],
                                    'num' => $reasonNumArr[$k],
                                    'dealMethod' => $dealMethodArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table."_reason",

                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'reasonId' => $reasonOptionArr[$k],
                                    'num' => $reasonNumArr[$k],
                                    'dealMethod' => $dealMethodArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }

                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    $this->commitTrans();
                    delete(array('table' =>  self::table."_reason", 'where' => " id not in ('" . implode("','", $reasonIdArr) . "') and orderId = '$id'"));
                    delete(array('table' =>  self::table."_item", 'where' => " id not in ('" . implode("','", $itemIdArr) . "') and orderId = '$id'"));
                    auditingFollow(array(
                        "type" => "工序巡检单",
                        "typeId" => $info['id'],
                        "text" => "【{$this->control['name']}】确认",
                    ));
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] != '已质检') {
                //按钮
                $button[] = [
                    "name" => "质检确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'commit', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];
            }
            if ($this->power(self::page, "cancel") && $info['state'] == '已质检') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            /*****质检项目********/
            $tr[] = ['质检项',  '结果选项', '备注'];
            $result = find(array('table' => self::table . "_item", 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $tr[] = [
                    $array['itemId'],
                    $array['options'],
                    $array['text'],
                ];
            }

            /*****不良原因********/
            $reason[] = ['不良原因', '不良数量', '处置方式', '备注'];
            $result = find(array('table' => self::table . "_reason", 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $reason[] = [
                    $array['reasonId'],
                    self::lostZero($array['num'],'numPrecision'),
                    $array['dealMethod'],
                    $array['text'],
                ];
            }
            $total_tr = [
                1 => self::lostZero(array_sum(array_column($result['array'],'num')), 'numPrecision'),
            ];
            $line = query('product_line', "id = '$info[targetId]'");
            $source = query($info['sourceTable'], "id = '$info[sourceId]'");
            $process = query('process',"id = '$source[processId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "关联派工单" => $info['sourceNo'],
                        "生产线" => $line['workshop'].'-'.$line['name'],
                        "工序" => $process['name'],
                        '计划开工日期'=>$source['startDate'],
                    ),
                    array(
                        "物料" => materialClass::getName($info['materialId']),
                        "计划数量" => self::lostZero($source['num'],'numPrecision'),
                        "检验数量(" . $info['unit'] . ")" => self::lostZero($info['num'],'numPrecision'),
                        "合格数量(" . $info['unit'] . ")" => self::lostZero($info['passNum'],'numPrecision'),
                    ),
                    array(
                        "不良数量(" . $info['unit'] . ")" =>$info['num'] - $info['passNum'],
                        "批次" => $info['batch'],
                    )
                ),
                '检验方案' => array(
                    array(
                        "质检方式" => '巡检',
                    ),
                    array(
                        '备注' => pre($info['text'])
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '质检项目',
                'html' => $this->listTable(array('tr' => $tr)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '不良明细',
                'html' => $this->listTable(array('tr' => $reason, 'total' => $total_tr)),
            ]);
            $data['html']   .= $this->tableShow(array(
                '系统信息' => array(
                    array(
                        "质检单号" => $info['orderNo'],
                        "质检人" => self::findStaff($info['checkId']),
                        "质检时间" => $info['checkTime']
                    ),
                ),
            ));
            $data['html'] = "<form name='detailForm'>".$data['html']."</form>";

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function js(): string
    {
        return <<<eof
<script>
//计算不合格数量
function getScrap(e){
    let total = Number($("#completeNum").html());
    let passNum = e.value;
    $("#scrap").html((total-passNum).toFixed(publicSettings.numPrecision.num))
}
function getDealMethod(e){
    let val = e.value;
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getDealMethod',{id:val},function (res){
               $(e).parent().parent().find(".dealMethod").html(res.data);
             },'json');
}
function addRow(e,qid){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{qid:qid},function (res){
                 $(e).parent().before(res.data);
             },'json');
}
</script>
eof;

    }
    /**
     * 获取处置方式
     * @return bool|string
     */
    public function getDealMethod(): bool|string
    {
        $id = $this->post('id');
        $quarantine_reason = query('quarantine_reason', "id = '$id'");
        $json['data'] = $quarantine_reason['method'];
        return json_encode($json,320);
    }

    /**
     * 批量质检
     */
    public function batchEdit(): bool|string
    {
        $idArr =$this->post('listId');

        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = '请选择数据';
        }else {
            $text='';
            $x = 0;
            foreach ($idArr as $id){
                $info = query('quality_order',"id = '$id'");
                if (empty($info['id'])){
                    $text.="未找到质检单<br>";
                }elseif($info['state'] !='待质检'){
                    $text.="单据编号【{$info['sourceNo']}】,批次【{$info['batch']}】不是待质检状态<br>";
                }else{
                    $warn = static::update([
                        "table" => self::table,
                        "field" => [
                            'state'=>'已质检',
                            'checkId'=>self::$stid,
                            'checkTime'=>$this->time,
                            'passNum' => $info['num'],
                        ],
                        "where" => "id = '$info[id]'"
                    ]);
                    if ($warn =='更新成功'){
                        $x++;
                        $text.="单据编号【{$info['orderNo']}】,批次【{$info['batch']}】质检成功<br>";
                        $all = find(array('table'=>self::table."_item","where"=>"orderId = '$info[id]' order by list asc"));
                        foreach ($all['array'] as  $array) {
                            static::update([
                                "table" => self::table."_item",
                                "field" => [
                                    'options' =>'合格',
                                ],
                                "where" => " id = '$array[id]'"
                            ]);
                        }
                    }else{
                        $text.="单据编号【{$info['orderNo']}】,批次【{$info['batch']}】质检失败<br>";
                    }
                }
            }
            if ($text){
                $this->logText(["type" => self::page, "text" => $this->control['name'].'批量质检情况如下：'.$text]);
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = '成功质检了'.$x.'条数据';
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已质检',
            'checkId'=>self::$stid,
            'checkTime'=>$this->time
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此质检单';
        } elseif ($info['state'] != '待质检') {
            $json['warn'] = '此质检单不是待质检状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "工序巡检单",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】确认",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 撤回
     */
    public function cancelEdit(){
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待质检',
            'checkId' => '',
            'checkTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此质检单';
        } elseif ($info['state'] != '已质检') {
            $json['warn'] = '此质检单不是已质检状态，无需撤回';
        }else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "工序巡检单",
                    "typeId" => $info['id'],
                    "text" =>  "【{$this->control['name']}】撤回",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认此质检单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm';
                $power = '';
                $word = true;
                break;
            case 'batch':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认批量质检所选择的数据？';
                $function = 'batchEdit';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此质检单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


}

